package com.leetroll.media.utils;

import com.leetroll.media.service.JobExecutor;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;
import ws.schild.jave.process.ProcessWrapper;
import ws.schild.jave.process.ffmpeg.DefaultFFMPEGLocator;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

@Slf4j
public class FfmpegUtil {

    private static void blockFfmpeg(BufferedReader br) throws IOException {
        String line;
        // 该方法阻塞线程，直至成功
        while ((line = br.readLine()) != null) {
            log.info(line);
        }
    }

    //ffmpeg -i input.mp4 -c:v libx264 -c:a aac -b:a 128k -hls_time 10 -hls_list_size 0 -hls_segment_filename "prefix/segment%03d.ts" -f hls output.m3u8
    public static void videoToM3u8(String inputFilePath, String outputPath, String name) throws Exception {
        ProcessWrapper process = new DefaultFFMPEGLocator().createExecutor();
        String m3u8OutputPath = outputPath + "\\" + name + ".m3u8";
        String tsOutputPath = outputPath + "\\" + "%08d.ts";
        process.addArgument("-i");
        process.addArgument(inputFilePath);
        process.addArgument("-c:v");
        process.addArgument("libx264");
        process.addArgument("-c:a");
        process.addArgument("copy");
        process.addArgument("-hls_time");
        process.addArgument("20");
        process.addArgument("-hls_list_size");
        process.addArgument("0");
        process.addArgument("-hls_segment_filename");
        process.addArgument(tsOutputPath);
//        process.addArgument("-f hls");
        process.addArgument(m3u8OutputPath);
        process.execute();
        try (BufferedReader br = new BufferedReader(new InputStreamReader(process.getErrorStream()))) {
            blockFfmpeg(br);
        }
    }

    /**
     * 获取视频时长
     */
    public static long getVideoDuration(String inputFilePath) throws Exception {
        long videoDuration = 0;
        ProcessWrapper process = new DefaultFFMPEGLocator().createExecutor();
        process.addArgument("-i");
        process.addArgument(inputFilePath);
        process.execute();
        try (BufferedReader br = new BufferedReader(new InputStreamReader(process.getErrorStream()))) {
            String line;
            while ((line = br.readLine()) != null) {
                if (line.contains("Duration:")) {
                    videoDuration = cutVideoDuration(line);
                    break;
                }
            }
        }
        return videoDuration;
    }

    /**
     * 截取ffmpeg视频信息中的视频时长
     */
    public static long cutVideoDuration(String line) {
        Pattern pattern = Pattern.compile("Duration: (..):(..):(..).");
        Matcher matcher = pattern.matcher(line);
        long duration = 0L;
        if (matcher.find()) {
            // 计算时长
            long hour = Long.parseLong(matcher.group(1));//group1为第一个括号内的内容
            long minute = Long.parseLong(matcher.group(2));//group2为第二个括号内容
            long second = Long.parseLong(matcher.group(3));//group3为第二个括号内容
            duration = hour * 3600 + minute * 60 + second;
        } else {
            System.out.println("NOT FOUND");
        }
        return duration;
    }


    /**
     * 将exr转化为视频
     * ffmpeg -y -apply_trc iec61966_2_1 -start_number 1 -i input.%04d.exr  -vcodec mpeg4 output.mp4
     */
    public static void exrToMp4(String exrFolder, String name) throws Exception {
        File folder = new File(exrFolder);
        File[] files = folder.listFiles();
        String fileName = files[0].getName().split("\\.")[0];
        Integer start = Integer.valueOf(fileName.substring(fileName.lastIndexOf("_") + 1));
        String prefix = fileName.substring(0, fileName.lastIndexOf("_") + 1);
        String filePath = exrFolder + "\\" + prefix + "%03d.exr";
        String outputPath = exrFolder + "\\" + name + ".mp4";
        ProcessWrapper process = new DefaultFFMPEGLocator().createExecutor();
        process.addArgument("-y");
        process.addArgument("-apply_trc");
        process.addArgument("iec61966_2_1");
        process.addArgument("-start_number");
        process.addArgument(String.valueOf(start));
        process.addArgument("-i");
        process.addArgument(filePath);
        process.addArgument("-vcodec");
        process.addArgument("libx264");
        process.addArgument(outputPath);
        process.execute();
        try (BufferedReader br = new BufferedReader(new InputStreamReader(process.getErrorStream()))) {
            blockFfmpeg(br);
        }
    }

    /**
     * 将exr转化为视频
     * ffmpeg -i input.mp4 -c:v libx264 -crf 20 -preset veryfast output.mp4
     */
    public static void change2H264(File file, String name) throws Exception {
        String outputPath = file.getParent() + "\\" + name + ".mp4";
        ProcessWrapper process = new DefaultFFMPEGLocator().createExecutor();
        process.addArgument("-i");
        process.addArgument(file.getAbsolutePath());
        process.addArgument("-c:v");
        process.addArgument("libx264");
        process.addArgument("-crf");
        process.addArgument("28");
        process.addArgument("-preset");
        process.addArgument("veryfast");
        process.addArgument(outputPath);
        process.execute();
        try (BufferedReader br = new BufferedReader(new InputStreamReader(process.getErrorStream()))) {
            blockFfmpeg(br);
        }
    }

    /**
     * 提取视频中的音频: ffmpeg -i '.\01-01 Course introduction.mp4' -vn 123.mp3
     */

    public static void main(String[] args) throws Exception {
//        videoToM3u8(
//                "C:\\Users\\quxiaoyu\\Desktop\\Create a 3D Robot in 15 Minutes ｜ Blender Tutorial.mp4",
//                "C:\\Users\\quxiaoyu\\Desktop\\test",
//                "test");

//        exrToMp4("F:\\_resources\\tutorial\\gumroad\\Compositing Academy - Gumroad - 200 FX Alpha VFX Asset Library\\4 Circle Shockwave Fast", "output");

        File folder = new File("F:\\_resources\\tutorial\\gumroad\\Compositing Academy - Gumroad - 200 FX Alpha VFX Asset Library\\入库");
        for (File sub : folder.listFiles()) {
            if (sub.getName().equals("Abstract GlassyFire")) continue;
            try {
                File mainFolder = Arrays.stream(sub.listFiles()).filter(file -> file.getName().equals("main")).collect(Collectors.toList()).get(0);
                File file = mainFolder.listFiles()[0];
                change2H264(file, "final");
                file.delete();
            } catch (Exception e) {
                log.error("error: >>>>>>>> {}", sub.getName());
            }
        }
    }
}
